<!DOCTYPE html>
<html>
<head>
  <title>JSON ADMIN</title>
  <meta charset="utf-8">
  <!--<link rel="stylesheet" type="text/css" href="//lib.f2ex.cn/cdn/foundation/6.3.1/css/foundation-flex.min.css">-->
  <!--<link rel="stylesheet" type="text/css" href="//lib.f2ex.cn/cdn/fontawesome/4.7.0/css/font-awesome.min.css">-->
  <script type="text/javascript" src="./jsoneditor.js"></script>
  <script type="text/javascript">
    var qiniu;
    
    JSONEditor.defaults.theme = 'html';
    JSONEditor.defaults.language = 'cn';
    JSONEditor.defaults.options.upload = function(type, file, cbs) {
      if (type === 'root.upload_fail') cbs.failure('Upload failed');
      else {

          if(qiniu == null) {qiniu = http("get_qiniu_token");}
          var fileName = "json/" + (new Date().getTime()) + '_' + file.name;
          var fd = new FormData();
          fd.append("key", fileName);
          fd.append("token", qiniu.token);
          fd.append("file", file);

          var xmlHttp = new XMLHttpRequest();
          xmlHttp.upload.addEventListener("progress", function(evt){
            cbs.updateProgress(Math.round(evt.loaded * 100 / evt.total));
          }, false);
          xmlHttp.open("POST", "http://upload-z1.qiniup.com");
          xmlHttp.onreadystatechange = function () { // 状态发生变化时，函数被回调
            if (xmlHttp.readyState === 4) { // 成功完成
                if (xmlHttp.status === 200) {
                    cbs.success(qiniu.domain + fileName);
                } else {
                    alert("ERROR: " + xmlHttp.status);
                }
            }
          };
          xmlHttp.send(fd);
      }
    };

  </script>
  <style type="text/css">
    html,body{width:100%;height:100%;margin:0;}
    #ja_preview{width:46%;height:100%;float:right;border-left:1px solid #eee;}
    #ja_preview_iframe{border:none;}
    #ja_preview_iframe.ja_iphone7{width:375px;height:667px;}
    #ja_editor_content{padding:1%;width:48%;float:left;}
  </style>
</head> 
<body>

<div id="ja_editor_content">
  网站：<select name="" id="ja_app"></select>
  页面：<select name="" id="ja_page"></select>
  版本：<select name="" id="ja_version"></select>
  <button id="ja_clean_versions">清空历史</button>

  <button id="ja_online">上线</button>
  
  <hr/>
  
  <div id="ja_valid_indicator"></div>
  <div id="ja_editor_holder"></div>
</div>

<div id="ja_preview">
  <iframe class="ja_iphone7" id="ja_preview_iframe" src=""></iframe> 
</div>


<script type="text/javascript">
      var app,page,version,editor,lastVersion;
      
      document.getElementById('ja_online').addEventListener('click',function() {
        var  versionSelect =document.getElementById("ja_version");
        if(!confirm("是否上线网站"+app+"页面"+page+"的版本"+versionSelect.options[versionSelect.selectedIndex].text+"！")) return;
        var res = http("online_app_www", {"app":app,"page":page,"version":version});
        alert("ok!");
      });
      document.getElementById('ja_clean_versions').addEventListener('click',function() {
        if(!confirm("是否清空网站"+app+"页面"+page+"的所有历史版本！")) return;
        var res = http("delete_app_versions", {"app":app,"page":page});
        renderVersions();
        alert("ok!");
      });


      document.getElementById('ja_app').addEventListener('change',function() {
        app = document.getElementById('ja_app').value;
        renderPages();
      });
      document.getElementById('ja_page').addEventListener('change',function() {
        page = document.getElementById('ja_page').value;
        renderVersions();
      });
      document.getElementById('ja_version').addEventListener('change',function() {
        version = document.getElementById('ja_version').value;
        editorReload();
      });
  

      function http(action, data){
        var responseData = {}
        var xmlHttp = new XMLHttpRequest();  
        xmlHttp.open("POST", "/index.php", false);  
        xmlHttp.onreadystatechange = function () { // 状态发生变化时，函数被回调
          if (xmlHttp.readyState === 4) { // 成功完成
              if (xmlHttp.status === 200) {
                  var data = JSON.parse(xmlHttp.responseText);
                  if (data.code != 0) {alert(data.data);}
                  responseData = data.data;
              } else {
                  alert("ERROR: " + xmlHttp.status);
              }
          } else {
              // HTTP请求还在继续...
          }
        };  
        xmlHttp.setRequestHeader("Content-Type","application/json;");
        xmlHttp.send(JSON.stringify({"c":"apps","a":action,"data":data}));
        return responseData;
      }
      
      function renderSelect(id, data){
        var select = document.getElementById(id)
        select.innerText = "";
  
        for(var i = data.length-1; i>=0; i--){
          var option = document.createElement("option");
          option.value = data[i].value;
          option.innerText = data[i].text;
          select.appendChild(option);
        }
      }
      
      function changeSelect(id, data){
        var select = document.getElementById(id)
        select.addEventListener('change', function(){}, false);
        select.value = data;
        var event = new UIEvent('change');
        select.dispatchEvent(event);
      }
      
      function renderApps(){
        var apps = http("get_apps", {});
        renderSelect('ja_app', apps);
        changeSelect('ja_app', apps.length > 0 ? apps[apps.length-1].value : '');
      }
      
      function renderPages(){
        var pages = http("get_app_pages", {"app":app});
        renderSelect('ja_page', pages);
        changeSelect('ja_page', pages.length > 0 ? pages[pages.length-1].value : '');
      }

      function renderVersions(isReload = true){
        var versions = http("get_app_versions", {"app":app, "page":page});
        renderSelect('ja_version', versions);
        if(isReload){
          changeSelect('ja_version', versions.length > 0 ? versions[versions.length-1].value : '');
        }else{
          version = versions.length > 0 ? versions[versions.length-1].value : '';
        }
      }
      
      function renderPreviewIframe(){
        console.log("preview", app, page, version);
        var src = "/index.php?c=preview&app="+app+"&page="+page+"&version="+version;
        document.getElementById('ja_preview_iframe').src = src;
      }
      
      function editorReload(){
        console.log("reload", app, page, version);
        if(editor != null){editor.destroy();}
        editor = new JSONEditor(document.getElementById('ja_editor_holder'),{
          schema: http("get_app_schema", {"app":app,"page":page}),
          startval: http("get_app_data", {"app":app,"page":page,"version":version}),
          disable_collapse: false,
          disable_edit_json: true,
          disable_properties: false,
          grid_columns: false,
          no_additional_properties: true
        });
        editor.on('change',function() {
          var errors = editor.validate();
          var indicator = document.getElementById('ja_valid_indicator');
          if(errors.length) {
            indicator.className = 'label alert';
            indicator.textContent = '无效';
          }else {
            indicator.className = 'label success';
            indicator.textContent = '有效';
            
            if(lastVersion==app+page+version){
              var data = editor.getValue();
              console.log("save", app,page,data);
              http("save_app_data", {"app":app,"page":page,"data":data});
              renderVersions(false);
            }
            lastVersion = app+page+version;
            
            renderPreviewIframe();
          }
        });
      }
      
      renderApps();
    
</script>

</body>
</html>